import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../config/httpHeaders.dart';

class HomePage extends StatefulWidget {
  @override
  createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  Future getCategories() async {
    final response = await http.get(
        'https://gold-tag-ms.juejin.im/v1/categories',
        headers: httpHeaders);
    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      throw Exception('Fail to load Categories');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return FutureBuilder(
      future: getCategories(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          var tabList = snapshot.data['d']['categoryList'];
          return CreatePage(
            tabList: tabList,
          );
        } else if (snapshot.hasError) {
          return Text("error1>>>>>>>>>>>>>>>:${snapshot.error}");
        } else {
          return new Container(
            color: new Color.fromRGBO(244, 245, 245, 1.0),
          );
        }
      },
    );
  }
}

class CreatePage extends StatefulWidget {
  final List tabList;
  @override
  CreatePage({Key key, this.tabList}) : super(key: key);
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new CreatePageState();
  }
}

class CreatePageState extends State<CreatePage>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new DefaultTabController(
      length: widget.tabList.length,
      child: new Scaffold(
          appBar: new AppBar(
            backgroundColor: new Color.fromRGBO(244, 245, 245, 1.0),
            automaticallyImplyLeading: false,
            titleSpacing: 0.0,
            title: new TabBar(
              indicatorSize: TabBarIndicatorSize.label,
              isScrollable: true,
              labelColor: Colors.blue,
              unselectedLabelColor: Colors.grey,
              tabs: widget.tabList.map((tab) {
                return new Tab(
                  text: tab["name"],
                );
              }).toList(),
            ),
          ),
          body: new TabBarView(
            children: widget.tabList.map((cate) {
              return new ArticlesList(categories: cate);
            }).toList(),
          )),
    );
  }
}

class ArticlesList extends StatefulWidget {
  final Map categories;

  @override
  ArticlesList({Key key, this.categories}) : super(key: key);

  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new ArticlesListState();
  }
}

class ArticlesListState extends State<ArticlesList> {
  List articleList;
  ScrollController _controller;

  Future getArticelList({int limit = 20, String category}) async {
    final String url =
        'https://timeline-merger-ms.juejin.im/v1/get_entry_by_rank?src=${httpHeaders['X-Juejin-Src']}&uid=${httpHeaders['X-Juejin-Uid']}&device_id=${httpHeaders['X-Juejin-Client']}&token=${httpHeaders['X-Juejin-Token']}&limit=$limit&category=$category';
    print(url);
    final response = await http.get(Uri.encodeFull(url));
    if (response.statusCode == 200) {
      return json.decode(response.body);
    } else {
      throw Exception('Failed to load post');
    }
  }

  getMoreArticeles(){
    _controller = new ScrollController();
    _controller.addListener(() {
      var maxScroll = _controller.position.maxScrollExtent;
      var pixels = _controller.position.pixels;
      if (maxScroll == pixels) {
        // load next page
        getArticelList(category: widget.categories['id']);
      }
    });
  }

  Future<Null> loadData({int limit = 20, String category}) async {
    await getArticelList(category: category);
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new RefreshIndicator(
      onRefresh: loadData,
      child: new FutureBuilder(
          future: getArticelList(category: widget.categories['id']),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              articleList = snapshot.data['d']['entrylist'];
              return new ListView.builder(
                itemCount: articleList.length,
                itemBuilder: (context, index) {
                  var item = articleList[index];
                  return createItem(item);
                },
                controller: _controller,
              );
            } else if (snapshot.hasError) {
              return new Center(
                child: new Text('网络异常'),
              );
            }
            return new CupertinoActivityIndicator();
          }),
    );
  }
}

Widget createItem(articleInfo) {
  var objectId = articleInfo['originalUrl']
      .substring(articleInfo['originalUrl'].lastIndexOf('/') + 1);
  final List tags = articleInfo['tags'];
  return new Container(
    margin: new EdgeInsets.only(bottom: 10.0),
    padding: new EdgeInsets.only(top: 10.0, bottom: 10.0),
    child: new FlatButton(
      padding: new EdgeInsets.all(0.0),
      onPressed: () {},
      child: new Column(
        children: <Widget>[
          new Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              new FlatButton(
                onPressed: null,
                child: new Row(
                  children: <Widget>[
                    new CircleAvatar(
                      backgroundImage:
                          new NetworkImage(articleInfo['user']['avatarLarge']),
                    ),
                    new Padding(padding: new EdgeInsets.only(right: 5.0)),
                    new Text(
                      articleInfo['user']['username'],
                      style: new TextStyle(color: Colors.black),
                    )
                  ],
                ),
              ),
              new Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [createTags(tags)],
              )
            ],
          )
        ],
      ),
    ),
  );
}

Widget createTags(List tags) {
  if (tags.length == 0) {
    return new Text('');
  }
  if (tags.length == 1) {
    var item = tags[0];
    return new FlatButton(
      onPressed: null,
      child: new Text(item['title']),
    );
  } else {
    var item = tags[0];
    var item1 = tags[1];
    return new Row(
      children: <Widget>[
        new FlatButton(
          onPressed: null,
          child: new Text(item['title']),
        ),
        new Text(
          '/',
          style: new TextStyle(
            color: Colors.grey,
          ),
        ),
        new FlatButton(
          onPressed: null,
          child: new Text(item1['title']),
        )
      ],
    );
  }
}
